package com.qianxp.authorize.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.qianxp.authorize.contrasts.AuthContrast;
import com.qianxp.authorize.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/** @author qianxiaopeng */
public class TokenUtils {

  private static final String TOKEN_NAME = "token_name";

  private static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);
  /**
   * 获取cookie中的对应的名称
   *
   * @param request 请求
   * @return
   */
  public static Cookie getToken(HttpServletRequest request) {
    List<Cookie> cookies =
        Arrays.stream(request.getCookies())
            .filter(cookie -> TOKEN_NAME.equals(cookie.getName()))
            .collect(Collectors.toList());
    if (!cookies.isEmpty()) {
      return cookies.get(0);
    }
    return null;
  }

  /**
   * 创建令牌
   * @param user
   * @param expireTime
   * @return
   */

  public static String createToken(User user, Date expireTime) {
    Algorithm algorithm = Algorithm.HMAC256(AuthContrast.SECRET_TOKEN);
    JWTCreator.Builder jwtCreatorBulider =
            JWT
                .create()
                .withIssuer(AuthContrast.ISSUER_TOKEN)
                .withExpiresAt(expireTime);
    Arrays.stream(User.class.getDeclaredFields())
        .forEach(
            field -> {
              field.setAccessible(true);
              try {
                Object f = field.get(user);
                if (Objects.nonNull(f)) {
                  jwtCreatorBulider.withClaim(field.getName(), String.valueOf(f));
                }
              } catch (IllegalAccessException e) {
                logger.error("获取field失败", e);
              }
            });

    return jwtCreatorBulider.sign(algorithm);
  }

  /**
   * 验证令牌的方法
   * @param token 令牌
   * @return
   * @throws Exception
   */
  public static Map<String, Claim> verifierToken(String token){
    Algorithm algorithm = Algorithm.HMAC256(AuthContrast.SECRET_TOKEN);
    JWTVerifier jwtVerifier = JWT.require(algorithm)
            .withIssuer(AuthContrast.ISSUER_TOKEN)
            .build();
      DecodedJWT jwt = jwtVerifier.verify(token);
      return jwt.getClaims();
  }

  /**
   * 设置token到cookie中
   * @param response
   * @param token
   */
  public static void setToken(HttpServletResponse response, String token) {
    Cookie cookie = new Cookie(TOKEN_NAME, token);
    response.addCookie(cookie);
  }
}
